package cn.life.business.user.service.impl;

import cn.life.business.role.dao.RoleDao;
import cn.life.business.role.entity.po.RolePo;
import cn.life.business.role.entity.vo.RoleVo;
import cn.life.business.user.entity.vo.LoginUserVo;
import cn.life.business.user.entity.vo.UserInfoVo;
import cn.life.common.entity.model.CMessage;
import cn.life.common.entity.model.MyUserInfo;
import cn.life.common.entity.po.ProjectPo;
import cn.life.common.support.SessionManager;
import cn.life.common.support.check.UserInterceptorHandler;
import cn.life.common.utils.EncryptPwdUtil;
import cn.life.common.utils.JwtUtil;
import cn.life.business.user.dao.UserDao;
import cn.life.business.user.entity.po.LoginUser;
import cn.life.business.user.entity.po.UserInfo;
import cn.life.business.user.entity.vo.RegisterUserVo;
import cn.life.business.user.service.UserService;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:    用户服务实现层
 * @Author 李佳明
 * @Date 2018/7/5 0005.6:56.
 */
@Service
@Transactional
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Override
    public CMessage registerUser(RegisterUserVo user) {
        //校验账号是否重复
        boolean result = userDao.verification(user);
        if(result){
            Long loginUserId = userDao.addLoginUser(user);
            if(loginUserId != 0){
                user.setLoginUserId(loginUserId);
                return userDao.addUserInfo(user) == 1 ? CMessage.registerSuccess():CMessage.fail("注册失败");
            }
            return CMessage.registerSuccess();
        }else{
            return CMessage.fail("该账号已存,请更换账号信息");
        }
    }

    @Override
    public CMessage login(HttpServletRequest request, HttpServletResponse response, LoginUser loginUser) throws IOException {
        //1.判断当前用户信息是否存在
        UserInfo userInfo = userDao.login(loginUser);
        //2.生成用户Token
        if(userInfo != null){
            //查询当前用户所属项目
            RolePo role = new RolePo();
            role.setUserId(userInfo.getUserId());
            RoleVo rolePo = roleDao.queryRoleDetail(role);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            userInfo.setFactoryId(rolePo.getFactoryId());
            userInfo.setProjectId(rolePo.getProjectId());
            userInfo.setLoginUserId(userInfo.getLoginUserId());
            String token = JwtUtil.generToken(userInfo.getUserId().toString(),null,userInfo.getUserId() + "," + userInfo.getUserName() + "," + userInfo.getUserSex() + "," + userInfo.getUserRole() + "," + rolePo.getProjectId() + "," + userInfo.getFactoryId() + "," + userInfo.getFactoryName() + "," + userInfo.getJgPushMark() + "," + userInfo.getHwPushMark());
            //3.创建session
            MyUserInfo myUserInfo = new MyUserInfo();
            BeanUtils.copyProperties(userInfo, myUserInfo);
            /*new SessionManager().createSession(request,response, myUserInfo);*/
            //用户访问过之后重新设置用户的访问时间，存储到cookie中，然后发送到客户端浏览器
            String cookieValue = rolePo.getFactoryId() + "-" + myUserInfo.getUserId() + "-" + userInfo.getFactoryName() + "-" + userInfo.getJgPushMark() + "-" + userInfo.getHwPushMark();
            cookieValue = EncryptPwdUtil.encryptPwd(cookieValue);
            Cookie cookie = new Cookie("factoryCookie",cookieValue);//创建一个cookie，cookie的名字是lastAccessTime
            cookie.setPath("/");
            //将cookie对象添加到response对象中，这样服务器在输出response对象中的内容时就会把cookie也输出到客户端浏览器
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.addCookie(cookie);

            //增加session
            myUserInfo.setFactoryId(rolePo.getFactoryId());
            myUserInfo.setProjectId(rolePo.getProjectId());
            String sessionKey = rolePo.getFactoryId() + "-" + myUserInfo.getUserId() + "-" + userInfo.getFactoryName() + "-" + userInfo.getJgPushMark() + "-" + userInfo.getHwPushMark();
            request.getSession().setAttribute(sessionKey,myUserInfo);

            if(loginUser.getHwPushMark() != null || loginUser.getJgPushMark() != null){
                //4.储存用户极光推送的标识
                if(loginUser.getJgPushMark() == null){
                    userInfo.setJgPushMark("");
                }else{
                    userInfo.setJgPushMark(loginUser.getJgPushMark());
                }
                if(loginUser.getHwPushMark() == null){
                    userInfo.setHwPushMark("");
                }else{
                    userInfo.setHwPushMark(loginUser.getHwPushMark());
                }

                int updateRes = userDao.updateUserInfo(userInfo);
            }
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("token",token);
            map.put("userInfo",userInfo);
            return CMessage.success("登陆成功",map);
        }
        return CMessage.fail("账号或密码错误，请重新登陆");
    }

    @Override
    public CMessage getUserInfo(UserInfo userInfo) {
        userInfo = userDao.getUserInfo(userInfo);
        return CMessage.successByData(userInfo);
    }

    @Override
    public CMessage updateUser(UserInfo userInfo) {
        return userDao.updateUserInfo(userInfo) == 1 ? CMessage.modifySuccess() : CMessage.fail("修改失败");
    }

    @Override
    public CMessage getUserList(UserInfo userInfo) {
        return CMessage.successByData(userDao.getUserList(userInfo));
    }

    @Override
    public CMessage queryDetail(UserInfo userInfo) {
        return CMessage.successByData(userDao.queryDetail(userInfo));
    }

    @Override
    public CMessage updateUserRole(UserInfoVo userInfoVo) {
        //1.修改用户基础信息，名称
        userDao.updateUserInfo(userInfoVo);
        //2.修改用户权限
        int projectRole = userDao.queryProjectRole(userInfoVo);
        if(projectRole == 0){
            userDao.addUserRole(userInfoVo);
        }else{
            userDao.updateUserRole(userInfoVo);
        }
        //3.修改用户账号密码
        userDao.updateLoginData(userInfoVo);
        return CMessage.modifySuccess();
    }

    @Override
    public CMessage deleteUser(UserInfo userInfo) {
        return userDao.deleteUser(userInfo) == 1 ? CMessage.removeSuccess() : CMessage.removeFail();
    }

    @Override
    public CMessage getProUserList(UserInfo userInfo) {
        return CMessage.successByData(userDao.getProUserList(userInfo));
    }

    @Override
    public CMessage updatePassword(LoginUserVo loginUserVo,MyUserInfo myUserInfo) {
        if (myUserInfo != null){
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(myUserInfo.getUserId());
            userInfo = userDao.getUserInfo(userInfo);
            LoginUser loginUser = userDao.getLoginUserInfo(userInfo.getLoginUserId());
            loginUserVo.setId(userInfo.getLoginUserId());
            loginUserVo.setLoginName(loginUser.getLoginName());
        }else{
            LoginUser loginUser = userDao.getLoginUserInfo(loginUserVo.getLoginName());
            if(!loginUser.getLoginPassword().equals(loginUserVo.getOldPassword())){
                return CMessage.fail("原密码不正确，请重新输入");
            }
        }
        return userDao.updatePassword(loginUserVo) == 1 ? CMessage.modifySuccess() : CMessage.modifyFail();
    }

    @Override
    public CMessage queryMaterialAuditUserList(ProjectPo projectPo) {
        List<UserInfo> userInfoList = userDao.queryMaterialAuditUserList(projectPo);
        return CMessage.successByData(userInfoList);
    }

    @Override
    public CMessage queryScheduleAuditUserList(ProjectPo projectPo) {
        List<UserInfo> userInfoList = userDao.queryScheduleAuditUserList(projectPo);
        return CMessage.successByData(userInfoList);
    }

    @Override
    public CMessage queryTechnologyManagerList(ProjectPo projectPo) {
        List<UserInfo> userInfoList = userDao.queryTechnologyManagerList(projectPo);
        return CMessage.successByData(userInfoList);
    }

    @Override
    public CMessage queryUserStatistics(ProjectPo projectPo) {
        List<Map<String, Object>> list = userDao.queryUserStatistics(projectPo);
        List<Map<String, Object>> numberMaps = new ArrayList<>();
        Map<String, Object> numberMap = new HashMap<>();
        String nextUserId = "";
        for(int i=list.size()-1; i>=0; i--){
            //下一用户Id
            if(i != 0){
                nextUserId = list.get(i-1).get("userId").toString();
            }
            //当前用户信息
            Map<String, Object> map = list.get(i);
            String userId = map.get("userId").toString();
            String userName = map.get("userName").toString();
            Integer status = (Integer)map.get("status");
            if(i == list.size()-1){
                if(status != null && status == 1){
                    //合格
                    numberMap.put("number",1);
                }else{
                    numberMap.put("number",0);
                }
                numberMap.put("userId",userId);
                numberMap.put("userName",userName);
                if(status == null){
                    numberMap.put("number",1);
                    numberMap.put("allNumber",1);
                }else{
                    numberMap.put("allNumber",1);
                }
            }else{

                if(numberMap.get("userId") == null){
                    if(status != null && status == 1){
                        //合格
                        numberMap.put("number",1);
                    }else{
                        numberMap.put("number",0);
                    }
                    numberMap.put("userId",userId);
                    numberMap.put("userName",userName);
                    if(status == null){
                        numberMap.put("number",1);
                        numberMap.put("allNumber",1);
                    }else{
                        numberMap.put("allNumber",1);
                    }
                }else{
                    if(status != null && status == 1){
                        //合格
                        numberMap.put("number",((Integer)numberMap.get("number") + 1));
                    }
                    numberMap.put("allNumber",((Integer)numberMap.get("allNumber") + 1));
                }
            }
            if(i != 0){
                if(!nextUserId.equals(userId)){
                    numberMaps.add(numberMap);
                    //当下一用户Id与当前用户不一致时，将当前统计的用户信息扔进map集合中
                    numberMap = new HashMap<>();
                }
            }else{
                numberMaps.add(numberMap);
            }


        }
        List<Map<String, Object>> statisticsMap = new ArrayList<>();
        for(Map<String, Object> map : numberMaps){
            Map<String, Object> map1 = new HashMap<>();
            map1.put("userId",map.get("userId"));
            map1.put("userName",map.get("userName"));
            Integer number = (Integer)map.get("number");
            Integer allNumber = (Integer)map.get("allNumber");
            System.out.println(Math.round(Float.valueOf(number) / Float.valueOf(allNumber) * 100));
            float s = Math.round(Float.valueOf(number) / Float.valueOf(allNumber) * 100);
            if(number == 0){
                s = 0;
            }
            map1.put("passRate",s);
            statisticsMap.add(map1);
        }
        return CMessage.successByData(statisticsMap);
    }
}
